package com.example.iread.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public final class WaveUtil {

    public static ByteArrayOutputStream getWavHeader(int length) {

        int sampleRate = 16000;
        int numChannels = 1;
        int bitRate = 16;

        // 写Wave头
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        try {
            // "RIFF" ChunkId 4位
            bos.write(getByteArrayByInt(0x46464952));
            // length 块长度 4位
            bos.write(getByteArrayByInt(length + 44 - 8));
            // "WAVE" Format 4位
            bos.write(getByteArrayByInt(0x45564157));

            // "fmt" SubChunk1 Id 4位
            bos.write(getByteArrayByInt(0x20746d66));

            // 16 SubChunk11 Size 4位
            bos.write(getByteArrayByInt(16));
            // AudioFormat PCM格式类别 2 位
            bos.write(getByteArrayByShort(1));
            // NumChannels 声道数 2位
            bos.write(getByteArrayByShort(1));
            // SampleRate 采样率 4位
            bos.write(getByteArrayByInt(sampleRate));
            // ByteRate 传输速率 4位
            bos.write(getByteArrayByInt((numChannels * bitRate / 8) * sampleRate));
            // BlockAlign 数据块对齐 2位
            bos.write(getByteArrayByShort(numChannels * bitRate / 8));
            // BitsPerSample 样本比特率 2位
            bos.write(getByteArrayByShort(bitRate));

            // "data" SubChunk2 Id 4位
            bos.write(getByteArrayByInt(0x61746164));
            // SubChunk2 Size 4位
            bos.write(getByteArrayByInt(length));
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

        return bos;
    }

    private static byte[] getByteArrayByShort(int data) {
        byte[] bytes = new byte[2];
        bytes[0] = (byte) (data & 0xFF);
        bytes[1] = (byte) (data >> 8 & 0xFF);
        return bytes;
    }

    private static byte[] getByteArrayByInt(int data) {
        byte[] bytes = new byte[4];
        bytes[0] = (byte) (data & 0xFF);
        bytes[1] = (byte) (data >> 8 & 0xFF);
        bytes[2] = (byte) (data >> 16 & 0xFF);
        bytes[3] = (byte) (data >> 24 & 0xFF);
        return bytes;
    }

}
